
package com.insigma.business.qrcode.merchant.bff.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import com.google.common.collect.Maps;


import com.insigma.business.common.dto.CurrentUser;
import com.insigma.business.common.service.CurrentUserService;
import com.insigma.business.common.utils.CurrentUserUtil;
import com.insigma.business.qrcode.common.dto.ActivityEvaluationTypeEnum;
import com.insigma.business.qrcode.common._consumer.CommonAdminAreaConsumer;
import com.insigma.business.qrcode.common.template.BasePagingResponse;
import com.insigma.business.qrcode.common.template.MemCacheManager;
import com.insigma.business.qrcode.common.util.AdminAreaCodeUtils;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.RpcContextUtil;
import com.insigma.business.qrcode.common.util.SessionUtils;
import com.insigma.business.qrcode.common.vo.BaseDeleteRequest;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.common.vo.SessionSoldier;
import com.insigma.business.qrcode.merchant.dto.request.*;
import com.insigma.business.qrcode.pay.dto.CareWelfareMerchantEvaluationCountDTO;
import com.insigma.business.qrcode.pay.dto.CareWelfareMerchantEvaluationDTO;
import com.insigma.business.qrcode.pay.dto.CareWelfareMerchantEvaluationSearchRequest;
import com.insigma.business.qrcode.soldier.dto.SimpleApiRequest;
import com.insigma.business.qrcode.soldier.dto.SoldierOuterLoginAccountDTO;
import com.insigma.business.qrcode.soldier.dto.gov.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.soldier.request.BaseGetRequest;
import com.insigma.business.qrcode.soldier._consumer.SoldierConsumer;
import com.insigma.business.qrcode.welfare.dto.*;
import com.insigma.business.qrcode.merchant._consumer.CareWelfareMerchantEvaluationConsumer;
import com.insigma.business.qrcode.merchant.bff.CareWelfareMerchantInfoBffProvider;
import com.insigma.business.qrcode.merchant._consumer.CareWelfareMerchantInfoConsumer;
import com.insigma.business.qrcode.welfare.util.LocationUtils;
import com.insigma.business.qrcode.welfare.util.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
@Component("careWelfareMerchantInfoBffProvider")
public class CareWelfareMerchantInfoBFFProviderImpl extends BaseProviderImpl implements CareWelfareMerchantInfoBffProvider {

    @Autowired
    private CareWelfareMerchantInfoConsumer careWelfareMerchantInfoConsumer;

    @Autowired
    private CommonAdminAreaConsumer commonAdminAreaConsumer;

    @Autowired
    private SoldierConsumer soldierConsumer;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private CareWelfareMerchantEvaluationConsumer careWelfareMerchantEvaluationConsumer;

    @Autowired
    private CurrentUserService currentUserService;

    @Override
    public BasePagingResponse<List<CareWelfareMerchantInfoDTO>> searchCareWelfareMerchantInfo(final CareWelfareMerchantInfoSearchRequest searchRequest) {

        final BasePagingResponse<List<CareWelfareMerchantInfoDTO>> basePagingResponse = new BasePagingResponse<>();
        serviceTemplate.execute(basePagingResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(searchRequest, "查询分页CareWelfareMerchantInfo的请求参数不能为空");
            }

            @Override
            public void executeService() {
                if (searchRequest.getShow() == null) {
                    searchRequest.setShow(true);
                }
                CurrentUser currentUser = CurrentUserUtil.getCurrentUser();
                if (!StringUtils.isBlank(currentUser.getLoginUserType())) {
                    searchRequest.setPublished(true);
                }
//                CommonAdminAreaDTO adminAreaOfEmployee = commonAdminAreaConsumer.findAdminAreaOfEmployee();
//                if (AdminAreaCodeUtils.getLevel(adminAreaOfEmployee.getId()) > 2) {
//                    searchRequest.setAdminAreaCode(adminAreaOfEmployee.getId());
//                }
                BasePagingResponse<List<CareWelfareMerchantInfoDTO>> listBasePagingResponse = careWelfareMerchantInfoConsumer.searchCareWelfareMerchantInfo(searchRequest);
                List<CareWelfareMerchantInfoDTO> dto = listBasePagingResponse.getDto();
                if (!CollectionUtils.isEmpty(dto)) {
                    for (CareWelfareMerchantInfoDTO merchantInfoDTO : dto) {
                        merchantInfoDTO.setQrCode(merchantInfoDTO.getPageQrCode());
                    }
                }
                BeanUtil.copyProperties(listBasePagingResponse, basePagingResponse);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.CARE_WELFARE_MERCHANT_INFO_SEARCH;
            }
        });

        return basePagingResponse;
    }

    @Override
    public BasePagingResponse<List<CareWelfareMerchantInfoDTO>> searchMerchantInfoBySoldier(CareWelfareMerchantInfoSearchRequest careWelfareMerchantInfoSearchRequest) {
        return null;
    }

    @Override
    public BasePagingResponse<List<CareWelfareMerchantInfoDTO>> getCareWelfareMerchantHotList(CareWelfareMerchantInfoSearchRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");

        SessionSoldier sessionSoldier = RpcContextUtil.getSessionSoldier();
        if (sessionSoldier != null) {
            request.setSoldierId(sessionSoldier.getUserId());
        }

        if (AdminAreaCodeEnum.HOT_CLICK.name().equals(request.getAdminAreaCode()) || AdminAreaCodeEnum.HOT_CLICK.name().equals(request.getSearchType())) {
            return getCareWelfareMerchantHotClickList(request);
        }

        BasePagingResponse<List<CareWelfareMerchantInfoDTO>> listBasePagingResponse = careWelfareMerchantInfoConsumer.searchMerchantInfoWithoutAuth(request);
        List<CareWelfareMerchantInfoDTO> dto = listBasePagingResponse.getDto();
        if (!CollectionUtils.isEmpty(dto)) {
            for (CareWelfareMerchantInfoDTO merchantInfoDTO : dto) {
                MerchantTypeEnum byEnumName = MerchantTypeEnum.getByEnumName(merchantInfoDTO.getType());
                merchantInfoDTO.setIcon(byEnumName.getImg());
            }
        }
        return listBasePagingResponse;
    }

    @Override
    public BasePagingResponse<List<CareWelfareMerchantInfoDTO>> getCareWelfareMerchantHotClickList(CareWelfareMerchantInfoSearchRequest request) {
        return null;
    }


    private boolean isFilterPass(CareWelfareMerchantInfoDTO merchantInfoDTO, CareWelfareMerchantInfoSearchRequest request) {
        if (!Boolean.TRUE.equals(merchantInfoDTO.getPublished())) {
            return false;
        }

        if (Strings.isNotBlank(request.getType())) {
            if (!request.getType().equals(merchantInfoDTO.getType())) {
                return false;
            }
            if (Strings.isNotBlank(request.getSubtype())) {
                if (!request.getSubtype().equals(merchantInfoDTO.getSubtype())) {
                    return false;
                }
            }
        }
        if (Strings.isNotBlank(request.getName())) {
            if (!merchantInfoDTO.getName().contains(request.getName())) {
                return false;
            }
        }

        if (Strings.isNotBlank(request.getAdminAreaCode()) && request.getAdminAreaCode().startsWith("33")) {
            if (!merchantInfoDTO.getAdminAreaCode().startsWith(AdminAreaCodeUtils.getCutdAreaCode(request.getAdminAreaCode()))) {
                return false;
            }
        }
        return true;
    }


    private Integer calculateDistance(Double latitude, Double longitude, Double sjLat, Double sjLng) {
        if (latitude == null || longitude == null || sjLat == null || sjLng == null) {
            return null;
        }

        double distance = LocationUtils.getDistance(latitude, longitude, sjLat, sjLng);
        return (int) distance;
    }

    private void expiredMerchant(String id) {
        if (Strings.isBlank(id)) {
            return;
        }

        Cache<String, Object> instance = MemCacheManager.getInstance(12, TimeUnit.HOURS);
        Object allItem = instance.getIfPresent("ALL_ITEM");
        if (allItem != null) {
            Map<String, CareWelfareMerchantInfoDTO> map = (Map<String, CareWelfareMerchantInfoDTO>) allItem;
            if (id.contains("-")) {
                id = id.substring(0, id.indexOf("-"));
            }
            map.remove(id);
        }


        Cache<String, Object> instance2 = MemCacheManager.getInstance(12, TimeUnit.HOURS);
        instance2.invalidate("HOT_CLICK_IDS");
    }

    private Map<String, CareWelfareMerchantInfoDTO> getCachedMapOfAllMerchant() {
        Cache<String, Object> instance = MemCacheManager.getInstance(12, TimeUnit.HOURS);
        try {
            Object allItem = instance.get("ALL_ITEM", new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    return Maps.newHashMap();
                }
            });
            return (Map<String, CareWelfareMerchantInfoDTO>) allItem;
        } catch (ExecutionException e) {
            log.error("error:{}", e);
        }
        return null;
    }

    private List<String> getCachedMerchantHotClickIds() {
        Cache<String, Object> instance = MemCacheManager.getInstance(12, TimeUnit.HOURS);
        try {
            Object hotClickIds = instance.get("HOT_CLICK_IDS", new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    return getLastWeekMerchantSort();
                }
            });
            List<String> list = (List<String>) hotClickIds;
            return list;
        } catch (ExecutionException e) {
            log.error("error:{}", e);
        }
        return null;
    }

    private List<String> getCachedMerchantHotClickIds(int pageNo, int pageSize) {
        Cache<String, Object> instance = MemCacheManager.getInstance(12, TimeUnit.HOURS);
        try {
            Object hotClickIds = instance.get("HOT_CLICK_IDS", new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    return getLastWeekMerchantSort();
                }
            });
            List<String> list = (List<String>) hotClickIds;
            List<String> page = paging(pageNo, pageSize, list);
            return page;
        } catch (ExecutionException e) {
            log.error("error:{}", e);
        }
        return null;
    }

    public static <T> List<T> paging(Integer pageNo, Integer pageSize, List<T> list) {
        if (list == null) {
            list = new ArrayList<T>();
        }
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageNo <= 0) {
            pageNo = 1;
        }

        int totalitems = list.size();
        List<T> pagingList = new ArrayList<T>();

        int totalNum = ((pageNo - 1) * pageSize) + pageSize > totalitems ? totalitems : ((pageNo - 1) * pageSize) + pageSize;
        for (int i = (pageNo - 1) * pageSize; i < totalNum; i++) {
            pagingList.add(list.get(i));
        }
        return pagingList;

    }


    private int getCachedMerchantHotClickTotalSize() {
        Cache<String, Object> instance = MemCacheManager.getInstance(12, TimeUnit.HOURS);
        try {
            Object hotClickIds = instance.get("HOT_CLICK_IDS", new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    return getLastWeekMerchantSort();
                }
            });
            List<String> list = (List<String>) hotClickIds;
            return list.size();
        } catch (ExecutionException e) {
            log.error("error:{}", e);
        }
        return 0;
    }

    private Object getLastWeekMerchantSort() {

        return new ArrayList<>();
    }

    @Override
    public BasePagingResponse<List<CareWelfareMerchantInfoDTO>> getCareWelfareMerchantRecommendList(final CareWelfareMerchantInfoSearchRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getId(), "请求不能为空");
        CareWelfareMerchantInfoDTO dto = getCareWelfareMerchantInfo(new BaseGetRequest(request.getId())).getDto();
        request.setType(dto.getType());
        return getCareWelfareMerchantHotList(request);
    }



    private BaseResponse<CareWelfareMerchantInfoDTO> getCareWelfareMerchantInfo(BaseGetRequest baseGetRequest) {
        CareWelfareMerchantInfoSearchRequest request = new CareWelfareMerchantInfoSearchRequest();
        request.setId((String) baseGetRequest.getId());
        return getCareWelfareMerchantInfo(request);
    }

    @Override
    public BaseResponse<CareWelfareMerchantInfoDTO> getCareWelfareMerchantInfo(final CareWelfareMerchantInfoSearchRequest request) {


        return null;
    }

    @Override
    public BaseResponse<String> insertCareWelfareMerchantInfo(CareWelfareMerchantInfoInsertRequest careWelfareMerchantInfoInsertRequest) {
        return null;
    }


    @Override
    public BaseResponse<Integer> checkMerchant(CareWelfareMerchantInfoUpdateRequest request) {
        return null;
    }

    @Override
    public BaseResponse<Integer> deleteCareWelfareMerchantInfo(BaseDeleteRequest deleteRequest) {
        return null;
    }

    @Override
    public BaseResponse<Boolean> publishWelfareMerchantInfo(SimpleApiRequest request) {
        return null;
    }

    @Override
    public BaseResponse<Integer> updateAllCode(CareWelfareMerchantInfoUpdateRequest careWelfareMerchantInfoUpdateRequest) {
        return null;
    }

    @Override
    public List<JSONObject> queryTop20(String adminAreaCode) {

        return new ArrayList<>();
    }


    @Override
    public BasePagingResponse<List<CareWelfareMerchantInfoDTO>> sjglSearchCareWelfareMerchantInfo(CareWelfareMerchantInfoSearchRequest careWelfareMerchantInfoSearchRequest) {
        return searchCareWelfareMerchantInfo(careWelfareMerchantInfoSearchRequest);
    }

    @Override
    public BaseResponse<CareWelfareMerchantInfoDTO> sjglGetCareWelfareMerchantInfo(CareWelfareMerchantInfoSearchRequest baseGetRequest) {
        return getCareWelfareMerchantInfo(baseGetRequest);
    }

    @Override
    public BaseResponse<String> sjglInsertCareWelfareMerchantInfo(CareWelfareMerchantInfoInsertRequest careWelfareMerchantInfoInsertRequest) {
        return null;
    }

    @Override
    public BaseResponse<Integer> sjglUpdateCareWelfareMerchantInfo(CareWelfareMerchantInfoUpdateRequest careWelfareMerchantInfoUpdateRequest) {
        return null;
    }

    @Override
    public BaseResponse<CareScanMerchantInfoResult> scanMerchantQr(SimpleApiRequest request) {
        return null;
    }

    @Override
    public BaseResponse<CareScanMerchantInfoResult> getMerchantUserMatchInfo(SimpleApiRequest request) {
        return null;
    }

    @Override
    public BaseResponse<String> insertCareWelfareMerchantEvaluation(CareWelfareMerchantEvaluationInsertRequest request) {

        BizCheckUtil.checkNotNull(request, "查询分页CareWelfareMerchantEvaluation的请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getMerchantId(), "商家id请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getRemark(), "评论不能为空");

//        String soldierUserId = SessionUtils.getSoldierUserId();
//        String cachedSoldierName = userUtils.getCachedSoldierName(soldierUserId);
        CurrentUser currentUser = CurrentUserUtil.getCurrentUser();
        request.setSoldierId(currentUser.getSoldierId());
        request.setSoldierName(currentUser.getRealName());
        request.setType(ActivityEvaluationTypeEnum.SOLDIER.name());
        return careWelfareMerchantEvaluationConsumer.insertCareWelfareMerchantEvaluation(request);
    }

    @Override
    public BasePagingResponse<List<CareWelfareMerchantEvaluationDTO>> searchCareWelfareMerchantEvaluation(CareWelfareMerchantEvaluationSearchRequest request) {
        BizCheckUtil.checkNotNull(request, "查询分页CareWelfareMerchantEvaluation的请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getMerchantId(), "merchantId请求参数不能为空");

        request.setSortKeyValueJoint("createDatetime_desc");
        BasePagingResponse<List<CareWelfareMerchantEvaluationDTO>> listBasePagingResponse = careWelfareMerchantEvaluationConsumer.searchCareWelfareMerchantEvaluation(request);
        List<CareWelfareMerchantEvaluationDTO> dto = listBasePagingResponse.getDto();
        if (CollectionUtil.isNotEmpty(dto)) {
            for (CareWelfareMerchantEvaluationDTO careWelfareMerchantEvaluationDTO : dto) {
                SoldierOuterLoginAccountDTO outer = soldierConsumer.getCachedOuterAccountBySoldierId(careWelfareMerchantEvaluationDTO.getSoldierId());
                if (outer != null) {
                    careWelfareMerchantEvaluationDTO.setAvatar(outer.getOuterSysAvatarUrl());
                    careWelfareMerchantEvaluationDTO.setSoldierName(outer.getOuterSysNickName());
                }
            }
        }

        return listBasePagingResponse;
    }

    @Override
    public BaseResponse<CareWelfareMerchantEvaluationCountDTO> countCareWelfareMerchantEvaluation(CareWelfareMerchantEvaluationSearchRequest request) {
        return careWelfareMerchantEvaluationConsumer.countCareWelfareMerchantEvaluation(request);
    }

    @Override
    public BaseResponse<CareMerchantStats> getMerchantStats(SimpleApiRequest request) {
        BizCheckUtil.checkNotNull(RpcContextUtil.getSessionGovEmployee(), "用户非法");

        return careWelfareMerchantInfoConsumer.getMerchantStats(request);    }

}
